package com.wangshuile.vue.controller;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.wangshuile.vue.commons.bean.PageResult;
import com.wangshuile.vue.commons.bean.Result;
import com.wangshuile.vue.entity.Article;
import com.wangshuile.vue.service.ArticleService;

/**
 * @实现跨域注解 
 * @origin="*"代表所有域名都可访问
 * @maxAge飞行前响应的缓存持续时间的最大年龄，简单来说就是Cookie的有效期 单位为秒
 * @若maxAge是负数,则代表为临时Cookie,不会被持久化,Cookie信息保存在浏览器内存中,浏览器关闭Cookie就消失
 * @author lqf
 * 
 * 添加vue-deltools@https://blog.csdn.net/qq_38967608/article/details/81211249
 */
@RestController
@RequestMapping("/article")
@CrossOrigin(origins = "*",maxAge = 3600)
public class ArticleController {
	
	@Autowired
	private ArticleService articleService;

	@PostMapping
    public Result<Article> saveArticle(@RequestBody Article article) {
         Article data=articleService.save(article);
         return Result.success(data);
    }

    @DeleteMapping("/{id}")
    public Result<String> deleteArticle(@PathVariable("id") String articleId) {
    	articleService.deleteById(articleId);
    	return Result.successMsg("删除成功");
    }

    @PutMapping("/{id}")
    public Result<Article> updateArticle(@PathVariable("id") String articleId, @RequestBody Article article) {
    	article.setId(articleId);
    	Article data=articleService.saveAndFlush(article);
        return Result.success(data);
    }

    @GetMapping("/{id}")
    public Result<Article> getArticleInfo(@PathVariable("id") String articleId) {
        Optional<Article> optional = articleService.findById(articleId);
        Article data=optional.orElseGet(Article::new);
        return Result.success(data);
    }

    @GetMapping("/list")
    public Result<PageResult<Article>> pageQuery(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
    	Page<Article> page=articleService.findAll(PageRequest.of(pageNum - 1, pageSize));
        return Result.success(new PageResult<Article>(page.getTotalElements(),page.getContent(),pageNum,pageSize));
    }

}
